# 直接从ui文件导入
import sys
import os
from docx import Document
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMessageBox, QFileDialog

app = QApplication(sys.argv)
window = uic.loadUi("kindle.ui")
window.show()

def select_input():
    in_file, _ = QFileDialog.getOpenFileName(window, '选择“My Clippings.txt”', '', 'All Files (*);; 文本文件 (*.txt)')
    window.in_entry.clear()
    window.in_entry.setText(in_file)

def select_output():
    #获取输出文件夹
    out_file = QFileDialog.getExistingDirectory(window, '选择文件夹保存')
    window.out_entry.clear()
    window.out_entry.setText(out_file)

window.inButton.clicked.connect(select_input)
window.outButton.clicked.connect(select_output)

def convert_success():
    msg = QMessageBox()
    # msg.setWindowTitle('转换成功')
    msg.setText('转换成功')
    msg.exec_()

def convert_clip():
    in_file = window.in_entry.text()
    out_file = window.out_entry.text()
    title = window.title_entry.text()
    export_position_time = window.position_time.isChecked()

    in_clippings = str(in_file)
    in_clippings_name = os.path.basename(in_clippings)
    #直接输出docx
    out_clippings = os.path.join(str(out_file), in_clippings_name+'.docx')

    out_clippings_format = out_clippings.split('.')[-1]

    # Kindle的My Clippings.txt中每条文摘以“==========”分割
    clippings = open(in_clippings, 'r').read().split('==========\n')

    # 以字典存文摘，书名为索引
    clip_out = {}

    # 最后一个clipping为空
    for i in clippings[:-1]:
        clip = i.strip().split('\n')
        book = clip[0].strip()
        position_time = clip[1].strip().split('|')
        position = position_time[0].strip()
        time = position_time[1].strip()
        time_position = time+' '+position
        note = '\n'.join(clip[2:]).strip()

        # 以书名为索引存入字典
        try:
            clip_out[book][time_position] = note
        # 若书名不存在，新建书名字典
        except:
            clip_out[book] = dict()
            clip_out[book][time_position] = note

    # 根据后缀输出不同格式
    if out_clippings_format == 'docx':
        # 输出docx格式
        document = Document('zh-template.docx')
        document.add_heading(title, level = 0)
        for k in clip_out.keys():
            document.add_heading(k, level = 1)
            for kk in clip_out[k].keys():
                if export_position_time:
                    document.add_paragraph(kk)
                    document.add_paragraph(clip_out[k][kk])
                else:
                    document.add_paragraph(clip_out[k][kk])
        document.save(out_clippings)
    else:
        # 若非docx，输出markdown格式
        with open('%s.md' %out_clippings, 'w') as out_md:
            out_md.write('---\ntitle: %s\n---\n\n' %title)
            for k in clip_out.keys():
                out_md.write('# %s\n\n' %k)
                for kk in clip_out[k].keys():
                    if export_position_time:
                        out_md.write('%s\n\n>%s\n\n' %(kk, clip_out[k][kk]))
                    else:
                        out_md.write('>%s\n\n' %(clip_out[k][kk]))
    # 成功提示
    convert_success()

window.convert.clicked.connect(convert_clip)
sys.exit(app.exec_())

# # 转ui为python，然后导入
# import sys
# from PyQt5.QtWidgets import QApplication, QMainWindow
# from kindle_qt import *

# class mywindow(QMainWindow, Ui_MainWindow):
#     def __init__(self, parent=None):
#         super(mywindow, self).__init__(parent)
#         self.setupUi(self)

# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     window = mywindow()
#     window.show()
#     sys.exit(app.exec_())